#process.py
#-*-coding:utf8-*-
import hashlib
import os,sys

class process:
    def CalcSha1(self,filepath):
        with open(filepath,'rb') as f:
            sha1obj = hashlib.sha1()
            sha1obj.update(f.read())
            sha1 = sha1obj.hexdigest()
            # print(sha1)
            return sha1

    def CalcMD5(self,filepath):
        with open(filepath,'rb') as f:
            md5obj = hashlib.md5()
            md5obj.update(f.read())
            md5 = md5obj.hexdigest()
            # print(md5)
            return md5

    def openCsv(self, path, header):
        with open(path, 'w') as f:
            f.write(header)
            print 'Create a CSV file successfully'

    def writeCsv(self, path, text):
        with open(path, 'a') as f:
            f.write(text)

class hashMD5(process): #普通继承
    def filehash(self,hashfile):
        if not os.path.exists(hashfile):
            hashfile = os.path.join(os.path.dirname(__file__),hashfile)
            if not os.path.exists(hashfile):
                print("cannot found file")
            else:
                process.CalcMD5(hashfile)
                process.CalcSha1(hashfile)
        else:
            process.CalcMD5(hashfile)
            process.CalcSha1(hashfile)

    def dirhash(self,hashfile):
        files = os.listdir(hashfile)
        for f in files:
            getcmd = os.path.join(hashfile, f)
            if os.path.isfile(getcmd):
                # fileSize = str(os.path.getsize(getcmd)) + ' B'#大小
                hash_md5 = process.CalcMD5(getcmd)#md5
                hash_sha1 = process.CalcSha1(getcmd)#sha1
                path = os.path.join(os.getcwd(), u'哈希校验.csv')
                text = getcmd.replace(firstPath, '.') + ','+ hash_md5 + ',' + hash_sha1 + '\r' # + fileSize +','
                process.writeCsv(path, text)
            else:
                self.dirhash(getcmd)

class hashMain():
    def __init(self, hashfile):
        self.hashfile = hashfile

    def main(self):
        global firstPath, process, hashMD5
        process = process()
        hashMD5 = hashMD5()
        if len(sys.argv)==2 :
            self.hashfile = sys.argv[1]  #传入文件路径
            if os.path.isfile(self.hashfile):
                hashMD5.filehash(self.hashfile)
            else:
                path = os.path.join(os.getcwd(), u'哈希校验.csv')
                header = '路径,MD5,sha1' + '\r'
                process.openCsv(path, header)
                firstPath = self.hashfile
                hashMD5.dirhash(self.hashfile)

# if __name__ == "__main__":
#     hashMain = hashMain()
#     hashMain.main()